import datetime
import time

import requests
import wechatpy
from flask import Blueprint, jsonify, request
from wechatpy.replies import TextReply

import config as cfg
from model.weixIn_subscribe import WeixinSubscribe
from model.weixin_dict import WeixinDict
from model.weixin_message import WeixinMessage
from model.weixin_qrcode import WeixinQrcode
from model.weixin_token import WeixinToken
from utils.work_db import get_session
from utils.work_log import get_logger
from utils.work_weixin import client

api = Blueprint('weixin_api', __name__, url_prefix='/api/v1/weixin')

log = get_logger(__name__)


# client = WeChatClient(
#     cfg.WX_SERVICE_CONFIG.get('appid'),
#     cfg.WX_SERVICE_CONFIG.get('secret'))


# zsEbzoNzRai8QvpUHrHiT4dKyCHnFvhp
# X4qnFLOzajwVucMycLmLPzL6aqmRM3iIAgwWqtRqJcy
@api.route('/message/send', methods=['GET', 'POST'])
def post_message():
    args = request.args
    data = request.data
    message = wechatpy.parse_message(data)
    msg = data
    log.info(msg)
    session = get_session()
    if message.type == 'text':
        # 数据持久化
        weixin_message = WeixinMessage()
        weixin_message.message_id = message.id
        weixin_message.source = message.source
        weixin_message.target = message.target
        weixin_message.create_time = message.create_time
        weixin_message.message_type = message.type
        weixin_message.content = message.content
        session.add(weixin_message)
        session.commit()
        if message.content == '二维码':
            q = session.query(WeixinQrcode)
            q = q.filter(WeixinQrcode.openid == message.source)
            _res = q.first()
            if _res is None:
                result = get_qrcode(message.source)
                ticket = result.ticket
                session.add(result)
                session.commit()
            else:
                ticket = _res.ticket
            text_reply = TextReply()
            text_reply.source = message.target
            text_reply.target = message.source
            text_reply.time = int(time.time())
            text_reply.content = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + ticket
            return text_reply.render()

    # 取消关注/关注
    if message.type == 'event' and message.event in ['unsubscribe', 'subscribe']:
        subscribe = WeixinSubscribe()
        subscribe.message_id = message.id
        subscribe.source = message.source
        subscribe.target = message.target
        subscribe.create_time = message.create_time
        subscribe.message_type = message.type
        subscribe.event = message.event
        session.add(subscribe)
        session.commit()

    # 用户关注
    if message.type == 'event' and message.event in ['subscribe_scan', 'subscribe']:
        result = session.query(WeixinDict).filter(WeixinDict.key == 'welcome').first()
        text_reply = TextReply()
        text_reply.source = message.target
        text_reply.target = message.source
        text_reply.time = int(time.time())
        text_reply.content = result.value
        return text_reply.render()

    # 扫描微信二维码
    if message.type == 'event' and message.event in ['subscribe_scan', 'scan']:
        subscribe = WeixinSubscribe()
        subscribe.message_id = message.id
        subscribe.source = message.source
        subscribe.target = message.target
        subscribe.create_time = message.create_time
        subscribe.message_type = message.type
        subscribe.event = message.event
        subscribe.scene_str = message.scene_id
        subscribe.ticket = message.ticket
        session.add(subscribe)
        session.commit()

    if message.type == 'event' and message.event == 'click':
        # 点击菜单事件
        result = session.query(WeixinDict).filter(WeixinDict.key == message.key).first()
        if result is None:
            return ''
        text_reply = TextReply()
        text_reply.source = message.target
        text_reply.target = message.source
        text_reply.time = int(time.time())
        text_reply.content = result.value
        return text_reply.render()

    return ''


@api.route('/access_token/get')
def get_access_token():
    """
    服务号 刷新access_token
    :return:
    """
    appid = cfg.WX_SERVICE_CONFIG.get('appid')
    now = int(time.time())
    session = get_session()
    q = session.query(WeixinToken)
    q = q.filter(WeixinToken.appid == appid)
    res = q.first()
    if res is not None and res.access_expire_time > now + 120:
        # token存在且没有过期,冗余两分钟
        return jsonify({'code': 1, 'msg': '获取token成功'})
    r = requests.get('https://api.weixin.qq.com/cgi-bin/token',
                     params={
                         'grant_type': 'client_credential',
                         'appid': appid,
                         'secret': cfg.WX_SERVICE_CONFIG.get('secret')
                     })
    # {"errcode":40013,"errmsg":"invalid appid"}
    # {'errcode': 40164, 'errmsg': 'invalid ip 121.69.1.10, not in whitelist hint: [BP7Wha02273612]'}
    # {'access_token': '17_ycS-ZVYXSAaHHSEPvkExXQnEhYmpsXuVLOdSxHCHs2KkO77zBGWqKOhBFaQPf0G0u8m_
    # euhOIQWinnGcIky8CPi8T4olwJuy_E3pQ1cNckqfbthiBUNFjm9YEaoFFCeACAMMJ', 'expires_in': 7200}
    result = r.json()
    if result.get('errcode') is None:
        # 成功

        if res is not None:
            res.access_token = result.get('access_token')
            res.access_expire_time = int(time.time()) + result.get('expires_in')
            res.update_time = datetime.datetime.now()
            session.commit()
        else:
            token = WeixinToken()
            token.appid = appid
            token.access_token = result.get('access_token')
            token.access_expire_time = int(time.time()) + result.get('expires_in')
            token.update_time = datetime.datetime.now()
            session.add(token)
            session.commit()
        return jsonify({'code': 1, 'msg': '获取token成功'})
    else:
        # 失败
        return jsonify({'code': -1, 'msg': result.get('errmsg')})


# @api.route('/qrcode/get', methods=['GET'])
# @login_required
def get_qrcode(openid):
    result = client.qrcode.create(
        {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": openid}}}
    )
    qrcode = WeixinQrcode()
    qrcode.openid = openid
    qrcode.ticket = result.get('ticket')
    qrcode.url = result.get('url')
    qrcode.update_time = datetime.datetime.now()

    return qrcode
